package com.chee.plant.client;

import java.net.InetSocketAddress;

import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.apache.mina.transport.socket.nio.SocketConnectorConfig;

import com.chee.plant.server.Message;

public class ClientSupport {
    private final IoHandler _handler;
    private IoSession _session;

    public ClientSupport(IoHandler handler) {
        this._handler = handler;
    }
    public boolean connect(SocketConnector connector, InetSocketAddress address) {
        if (_session != null && _session.isConnected()) {
            throw new IllegalStateException("Already connected. Disconnect first.");
        }
        try {
            SocketConnectorConfig config = new SocketConnectorConfig();
            ConnectFuture future1 = connector.connect(address, _handler, config);
            future1.join();
            if (!future1.isConnected()) { return false; }
            _session = future1.getSession();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public void sendMessage(Message message) {
    	String content = message.getContent(); 
        _session.write(content);
    }
    public void quit() {
        if (_session != null) {
            _session.close();
        }
    }

}
